package com.leadingsoft.pwxk.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionLikeType;
import com.leadingsoft.pwxk.model.CentralPoint;
import com.leadingsoft.pwxk.repository.CentralPointRepository;
import com.leadingsoft.pwxk.repository.RegionCodeAllRepository;

@Configuration
public class InitData {

	@Autowired
	ObjectMapper objectMapper;

	@Autowired
	CentralPointRepository cpRepository;

	@Autowired
	RegionCodeAllRepository regionCodeAllRepository;

	@PostConstruct
	public void Init() throws JsonParseException, JsonMappingException, IOException {
		initCentralPoint();
		//initRegionCodeAll();
	}

	private void initCentralPoint() throws JsonParseException, JsonMappingException, IOException {
		if (null != cpRepository && cpRepository.count() == 0) {
			List<CentralPoint> cps = getListFromJson("CentralPoint", CentralPoint.class);
			cpRepository.saveAll(cps);
		}
	}

	private <T> List<T> getListFromJson(String name, Class<T> c)
			throws JsonParseException, JsonMappingException, IOException {
		InputStream iStream = null;
		iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("initdata/" + name + ".json");
		CollectionLikeType type = objectMapper.getTypeFactory().constructCollectionLikeType(List.class, c);
		return objectMapper.readValue(iStream, type);
	}

	
}
